package com.zx.BookSeaReader.ui.bookinfo;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ScrollView;

import com.bumptech.glide.Glide;
import com.zx.BookSeaReader.R;
import com.zx.BookSeaReader.base.BasePresenter;
import com.zx.BookSeaReader.callback.ResultCallback;
import com.zx.BookSeaReader.common.APPCONST;
import com.zx.BookSeaReader.enums.BookSource;
import com.zx.BookSeaReader.greendao.entity.Book;
import com.zx.BookSeaReader.greendao.entity.BookCommentBean;
import com.zx.BookSeaReader.greendao.entity.BookLabelBean;
import com.zx.BookSeaReader.greendao.entity.UserBean;
import com.zx.BookSeaReader.greendao.service.BookService;
import com.zx.BookSeaReader.greendao.service.CommentService;
import com.zx.BookSeaReader.greendao.service.UserService;
import com.zx.BookSeaReader.ui.home.MainActivity;
import com.zx.BookSeaReader.ui.read.ReadActivity;
import com.zx.BookSeaReader.util.Constant;
import com.zx.BookSeaReader.util.StringHelper;
import com.zx.BookSeaReader.util.StringUtils;
import com.zx.BookSeaReader.util.TextHelper;
import com.zx.BookSeaReader.webapi.BookStoreApi;
import com.zx.BookSeaReader.widget.itemdecoration.DividerItemDecoration;
import com.zx.BookSeaReader.widget.itemdecoration.FullyLinearLayoutManager;

import java.util.List;
import java.util.UUID;

import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;


public class BookInfoPresenter implements BasePresenter {

    private BookInfoActivity mBookInfoActivity;
    private Book mBook;
    private UserBean userBean;
    private BookService mBookService;
    private CommentService mCommentService;
    private BookCommentAdapter mBookCommentAdapter;
    private String source;
    private boolean isSubscribed=false;
    private List<BookCommentBean> mBookComments;
    private String fromRead;
    private BookCommentBean hotComment;
    private Handler mHandle = new Handler(message -> {
        switch (message.what){
            case 1:
                init();
                break;
            case 2:
                mBookInfoActivity.getScroll().fullScroll(ScrollView.FOCUS_UP);
                break;
        }
        return false;
    });

    public BookInfoPresenter(BookInfoActivity bookInfoActivity){
        mBookInfoActivity  = bookInfoActivity;
        mBookService = new BookService();
        mCommentService = new CommentService();
        mBookCommentAdapter=new BookCommentAdapter();
    }


    @Override
    public void start() {
        mBook = (Book) mBookInfoActivity.getIntent().getSerializableExtra(APPCONST.BOOK);
        fromRead = mBookInfoActivity.getIntent().getStringExtra(APPCONST.READ);
        if(fromRead!=null){
            mBookInfoActivity.getBtnAddBookcase().setVisibility(View.GONE);
            mBookInfoActivity.getBtnReadBook().setVisibility(View.GONE);;

        }else {
            mBookInfoActivity.getBtnReadBook().setVisibility(View.VISIBLE);;
            mBookInfoActivity.getBtnAddBookcase().setVisibility(View.VISIBLE);
        }
        //TextHelper.showLongText(fromRead+"");
        userBean=(UserBean) mBookInfoActivity.getIntent().getSerializableExtra(APPCONST.USER);
        mBookInfoActivity.getRvComment().setLayoutManager(new FullyLinearLayoutManager(mBookInfoActivity));
        mBookInfoActivity.getRvComment().addItemDecoration(new DividerItemDecoration(mBookInfoActivity));
        mBookInfoActivity.getRvComment().setAdapter(mBookCommentAdapter);
        //TextHelper.showText(userBean.getUsername());
        if (isBookCollected()){
            if (StringHelper.isEmpty(mBook.getSource()) || BookSource.tianlai.toString().equals(mBook.getSource())){
                source="天籁小说网";
            }else if(BookSource.biquge.toString().equals(mBook.getSource())){
                source="笔趣阁";
            }
            init();
        }else {
            if (StringHelper.isEmpty(mBook.getSource()) || BookSource.tianlai.toString().equals(mBook.getSource())){
                source="天籁小说网";
                mBook.setId(UUID.randomUUID().toString());
                mBook.setIsCollect(false);
                init();

            }else if(BookSource.biquge.toString().equals(mBook.getSource())){
                source="笔趣阁";
                getData();
            }

        }

    }
    public void scrollUp(){
        mHandle.sendMessage(mHandle.obtainMessage(2));
    }

    private void getData(){
        BookStoreApi.getBookInfo(mBook, new ResultCallback() {
            @Override
            public void onFinish(Object o, int code) {
                mBook = (Book)o;
                mBook.setId(UUID.randomUUID().toString());
                mBook.setIsCollect(false);
                mHandle.sendMessage(mHandle.obtainMessage(1));
            }

            @Override
            public void onError(Exception e) {
                TextHelper.showText(e.getMessage());

            }
        });


    }
    private void initAdapter(){
        mBookComments=mCommentService.getBookComment(mBook);
        mBookCommentAdapter.refreshItems(mBookComments);
        hotComment=mCommentService.getBookHotComment(mBook);
        if(hotComment==null){
            mBookInfoActivity.getRlComment().setVisibility(View.GONE);
        }else{
            mBookInfoActivity.getTvFloor().setText(hotComment.getFloorCount()+"楼");
            mBookInfoActivity.getTvAuthorName().setText(hotComment.getUsername());
            mBookInfoActivity.getTvCommentTime().setText(StringUtils.dateConvert(hotComment.getCreateTime(), Constant.FORMAT_BOOK_DATE));
            mBookInfoActivity.getTvContent().setText(hotComment.getContent());
            mBookInfoActivity.getTvLikeCount().setText(hotComment.getLikeCount()+"");
            mBookInfoActivity.getRlComment().setVisibility(View.VISIBLE);
        }
    }

    public void initButton(){
        isSubscribed=mBookService.isSubscribe(mBook,userBean);
        if(isSubscribed){
            mBookInfoActivity.getBtnAddBookcase().setText("取消订阅");
            //修改背景
            Drawable drawable = mBookInfoActivity.getResources().getDrawable(R.drawable.shape_common_gray_corner);
            mBookInfoActivity.getBtnAddBookcase().setBackground(drawable);
            //设置图片
            mBookInfoActivity.getBtnAddBookcase().setCompoundDrawables(ContextCompat.getDrawable(mBookInfoActivity, R.drawable.ic_book_list_delete), null,
                    null, null);
            mBookInfoActivity.getBtnReadBook().setText("继续阅读");

        }else {
            mBookInfoActivity.getBtnAddBookcase().setText("订阅");
            mBookInfoActivity.getBtnReadBook().setText("开始阅读");
        }
    }

    private void init(){
        //TextHelper.showLongText(mBook.getId()+"书籍");
       // mHandle.sendMessage(mHandle.obtainMessage(2));

        //TextHelper.showLongText(isSubscribed+"");
        initAdapter();
        //mBookInfoActivity.refreshComment(mBookComments);
        mBookInfoActivity.getTvTitleText().setText(mBook.getName());
        mBookInfoActivity.getTvBookAuthor().setText(mBook.getAuthor());
        mBookInfoActivity.getTvBookDesc().setText(mBook.getDesc());
        mBookInfoActivity.getTvBookType().setText(" | "+mBook.getType());
        mBookInfoActivity.getTvBookName().setText(mBook.getName());
        mBookInfoActivity.getTvBookSource().setText(source);
        mBookInfoActivity.getTvLatelyUpdate().setText("最近更新："+StringUtils.dateConvert(mBook.getUpdateDate(), Constant.FORMAT_FILE_DATE));
        mBookInfoActivity.getTvNewestChapter().setText(mBook.getNewestChapterTitle());
        mBookInfoActivity.getRlRefresh().setBackground(ContextCompat.getDrawable(mBookInfoActivity,R.color.white));
        //mBookInfoActivity.getRlRefresh().setVisibility(View.GONE);
        mBookInfoActivity.getRlRefresh().setVisibility(View.VISIBLE);
        mBookInfoActivity.getRlRefresh().showFinish();
        initButton();

       // mHandle.sendMessage(mHandle.obtainMessage(2));

        mBookInfoActivity.getLlTitleBack().setOnClickListener(view -> mBookInfoActivity.finish());
        mBookInfoActivity.getTvAddComment().setOnClickListener(view ->{
            if(!mBook.getIsCollect()){
                TextHelper.showLongText("你未阅读过该书籍！无法评论");
            }else {
                addComment();
            }
        });

        mBookInfoActivity.getBtnAddBookcase().setOnClickListener(view -> {
            if (!isSubscribed){
                if (!mBook.getIsCollect()){
                    mBook.setIsLocal(false);
                    mBook.setIsCollect(true);
                   // mBook.setRecommend(1);
                    mBookService.addBookAndSub(mBook,userBean);
                }else{
                    mBookService.addSubscribe(mBook.getId(),userBean);
                }

                TextHelper.showText("成功加入书架");
                mBookInfoActivity.getBtnAddBookcase().setText("取消订阅");
                Drawable drawable = mBookInfoActivity.getResources().getDrawable(R.drawable.shape_common_gray_corner);
                mBookInfoActivity.getBtnAddBookcase().setBackground(drawable);
                //设置图片
                mBookInfoActivity.getBtnAddBookcase().setCompoundDrawables(ContextCompat.getDrawable(mBookInfoActivity, R.drawable.ic_book_list_delete), null,
                        null, null);
                mBookInfoActivity.getBtnReadBook().setText("继续阅读");
                isSubscribed=true;
            }else {

                mBookService.deleteSub(mBook.getId(),userBean);
                TextHelper.showText("成功移除书籍");
                mBookInfoActivity.getBtnAddBookcase().setText("订阅");
                Drawable drawable = mBookInfoActivity.getResources().getDrawable(R.drawable.selector_btn_book_list);
                mBookInfoActivity.getBtnAddBookcase().setBackground(drawable);
                //设置图片
                mBookInfoActivity.getBtnAddBookcase().setCompoundDrawables(ContextCompat.getDrawable(mBookInfoActivity, R.drawable.ic_book_list_add), null,
                        null, null);
                mBookInfoActivity.getBtnReadBook().setText("开始阅读");
                isSubscribed=false;
            }

        });
        mBookInfoActivity.getBtnReadBook().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mBook.setLastRead( StringUtils.
                        dateConvert(System.currentTimeMillis(), Constant.FORMAT_BOOK_DATE));
                if(mBook.getIsCollect()){
                    mBookService.updateEntity(mBook);
                }
                Intent intent = new Intent(mBookInfoActivity, ReadActivity.class);
                intent.putExtra(APPCONST.BOOK,mBook);
                intent.putExtra(APPCONST.USER, userBean);
                mBookInfoActivity.startActivity(intent);

            }
        });
        //评论的长点击事件
        mBookCommentAdapter.setOnItemLongClickListener(
                (v, pos) -> {
                    //开启AlterDialog
                    openItemDialog(mBookCommentAdapter.getItem(pos));
                    return true;
                }
        );

        Glide.with(mBookInfoActivity)
                .load(mBook.getImgUrl())
                .into(mBookInfoActivity.getIvBookImg());
    }
    private void openItemDialog(BookCommentBean commentBean) {
        String[] menus;
        menus = mBookInfoActivity.getResources().getStringArray(R.array.menu_long_comment_click);
        AlertDialog commentBeanDialog = new AlertDialog.Builder(mBookInfoActivity)
                .setTitle(commentBean.getContent())
                .setAdapter(new ArrayAdapter<String>(mBookInfoActivity,
                                android.R.layout.simple_list_item_1, menus),
                        (dialog, which) -> onItemMenuClick(menus[which], commentBean))
                .setNegativeButton(null, null)
                .setPositiveButton(null, null)
                .create();

        commentBeanDialog.show();
    }

    private void onItemMenuClick(String which, BookCommentBean commentBean) {
        switch (which) {
            //点赞
            case "点赞":
                int likeCount = commentBean.getLikeCount()+1;
                commentBean.setLikeCount(likeCount);
                mCommentService.updateEntity(commentBean);
                TextHelper.showText("点赞成功");
                initAdapter();

                break;
            //删除
            case "删除":
                if(userBean.getAdmin()!=1){
                    TextHelper.showLongText("你不是管理员无法删除评论");
                }else {
                    mCommentService.deleteEntity(commentBean);
                    TextHelper.showText("删除成功");
                }
                break;
            default:
                break;
        }
    }

    /**
     * 添加评论
     * @param
     */
    private void addComment(){
        final EditText editText = new EditText(mBookInfoActivity);
        AlertDialog.Builder editDialog = new AlertDialog.Builder(mBookInfoActivity);
        //editDialog.setIcon(R.mipmap.ic_launcher_round);
        editDialog.setTitle("输入评论内容").setView(editText);
        editDialog.setPositiveButton("发送", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String content = editText.getText().toString();
                int size = mBookComments.size()+1;
                mCommentService.addComment(mBook,userBean,content,size);
                TextHelper.showText("添加评论成功");
                initAdapter();
//                mBookComments=mCommentService.getBookComment(mBook);
//                mBookCommentAdapter.refreshItems(mBookComments);
               // mBookInfoActivity.refreshComment(mBookComments);
            }
        });
        editDialog.show();
    }

    private boolean isBookCollected(){
        Book book = mBookService.findBookByAuthorAndName(mBook.getName(),mBook.getAuthor());

        if (book == null){

            return false;
        }else {
            mBook=book;
           // TextHelper.showLongText("哈哈哈"+mBook.getId());
            return true;
        }
    }


}
